package com.yunxi.service.dubboService.impl.sto;

import com.alibaba.cloud.context.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.yunxi.core.util.BeanTools;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.model.sto.StoManage;
import com.yunxi.service.localService.CodeCreateService;
import com.yunxi.service.localService.sto.StoManageService;
import com.yunxi.sto.pojo.*;
import com.yunxi.sto.service.StoManageDubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 仓库结构管理 服务实现类
 * </p>
 *
 * @author caoYong
 * @since 2019-05-14
 */
public class StoManageDubboServiceImpl implements StoManageDubboService {

    @Autowired
    @Qualifier(value = "stoManageServiceImpl")
    StoManageService stoManageService;

    @Autowired
    @Qualifier(value = "codeCreateServiceImpl")
    CodeCreateService codeCreateService;


    @Override
    public StoManageVO getById(String id) {
        StoManage stoManage = stoManageService.getById(id);
        StoManageVO stoManageVO = new StoManageVO();
        BeanTools.copyProperties(stoManageVO,stoManage);
        return stoManageVO;
    }

    @Override
    public ApiResult saveOrUpdate(StoManageEditVO stoManageEditVO) throws Exception {
        String oldStorageName = null;
        String newStorageName = stoManageEditVO.getStorageName();
        StoManage stoManage = stoManageService.getById(stoManageEditVO.getStorageId());
        String pid = stoManageEditVO.getPid();
        if(stoManage != null){
            oldStorageName = stoManage.getStorageName();
        }
        else{
            stoManage = new StoManage();
        }
        BeanTools.copyProperties(stoManage,stoManageEditVO);
        //新增仓库,获取系统生成的仓库编号
        if(stoManage.getStorageId() == null){
            //1主机厂 2渠道商
            String prefix = "";
            if(stoManage.getStorageOrgType() != null && stoManage.getStorageOrgType().equals("2")){
                prefix = "PST";
            }
            else {
                prefix = "FST";
            }
            String code = codeCreateService.createCode(prefix, 4);
            stoManage.setStorageCode(code);
            stoManageEditVO.setStorageCode(code);
        }
        //设置仓库全名
        setStorageFullName(pid,stoManage);
        if(stoManage.getStorageId() == null){
            stoManageService.saveOrUpdate(stoManage);
        }
        else{
            stoManageService.updateById(stoManage);
        }
        //当上级仓库名称变更,则所有下级仓库全名变更
        updateFullName(oldStorageName, newStorageName, stoManage);

        return ResponseUtil.ok("success");
    }

    /**
     * 更改仓库全名
     * @param oldStorageName
     * @param newStorageName
     * @param stoManage
     * @throws Exception
     */
    private void updateFullName(String oldStorageName, String newStorageName, StoManage stoManage) throws Exception {
        if(StringUtils.isNotEmpty(oldStorageName) && !oldStorageName.equals(newStorageName)){
            //获取所有下级仓库id
            List<String> list = stoManageService.getChildStorageId(stoManage.getStorageId());
            String storageType = stoManage.getStorageType();
            if(list != null && list.size() > 0){
                for(String id : list){
                    StoManage stoManage1 = stoManageService.getById(id);
                    String storageFullName = stoManage1.getStorageFullName();
                    if(StringUtils.isNotEmpty(storageFullName)){
                        String[] split = storageFullName.split("-");
                        split[Integer.parseInt(storageType)-1] = newStorageName;
                        String join = org.apache.commons.lang3.StringUtils.join(split, "-");
                        stoManage1.setStorageFullName(join);
                        stoManageService.saveOrUpdate(stoManage1);
                    }
                }
            }
        }
    }

    /**
     * 判断名称不可重复
     * @param stoManageEditVO
     * @throws Exception
     */
    private void checkStorageName(StoManageEditVO stoManageEditVO) throws Exception {
        QueryWrapper<StoManage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("STORAGE_NAME",stoManageEditVO.getStorageName());
        if(stoManageEditVO.getStorageId() != null){
            queryWrapper.ne("STORAGE_ID",stoManageEditVO.getStorageId());
        }
        List<StoManage> list = stoManageService.list(queryWrapper);
        if(list != null && list.size() > 0){
            throw new Exception("操作失败,名称:"+stoManageEditVO.getStorageName()+"已存在!");
        }
    }

    /**
     * 设置仓库全名
     * @param pid
     * @param stoManage
     * @throws Exception
     */
    private void setStorageFullName(String pid,StoManage stoManage) throws Exception {
        StoManageEditVO storageNames = stoManageService.getStorageNames(pid);
        String storageType = stoManage.getStorageType();
        if(StringUtils.isNotEmpty(storageType) && storageType.equals("1")){
            stoManage.setStorageFullName(stoManage.getStorageName());
        }
        if(storageNames != null){
            String ck = storageNames.getCk();
            String kq = storageNames.getKq();//仓库
            String kd = storageNames.getKd();//库区
            String kw = storageNames.getKw();//库道
            switch (storageType){
                case "1":
                    stoManage.setStorageFullName(kw);
                    break;
                case "2":
                    stoManage.setStorageFullName(kw+"-"+stoManage.getStorageName());
                    break;
                case "3":
                    stoManage.setStorageFullName(kd+"-"+kw+"-"+stoManage.getStorageName());
                    break;
                case "4":
                    stoManage.setStorageFullName(kq+"-"+kd+"-"+kw+"-"+stoManage.getStorageName());
                    break;
                default:
                    break;
            }
            // 校验库位名称不可重复
            checkStorageFourName(stoManage);
        }
    }

    /**
     * 校验相同仓库类型,编号不能相同
     * @param stoManageEditVO
     */
    private Boolean checkCodeIsExsit(StoManageEditVO stoManageEditVO) {
        Boolean isExsit = false;
        if(stoManageEditVO.getStorageCode() != null && StringUtils.isNotEmpty(stoManageEditVO.getStorageCode())){
            QueryWrapper queryWrapper = new QueryWrapper();
            if(stoManageEditVO.getStorageId() != null && StringUtils.isNotEmpty(stoManageEditVO.getStorageId())){
                queryWrapper.ne("STORAGE_ID",stoManageEditVO.getStorageId());
            }
            queryWrapper.eq("STORAGE_TYPE",stoManageEditVO.getStorageType());
            queryWrapper.eq("STORAGE_CODE",stoManageEditVO.getStorageCode());
            List list = stoManageService.list(queryWrapper);
            if(list != null && list.size() > 0){
                isExsit = true;
            }
        }
        return isExsit;
    }

    @Override
    public void removeById(String id) {
    stoManageService.removeById(id);
    }

    @Override
    public void del(List<String> list,String userId)throws Exception {
        stoManageService.disabled(list,userId);
    }

    @Override
    public void reset(List<String> list,String userId) {
        stoManageService.delAndReset(list,0,userId);
    }

    @Override
    public void frozen(List<VehicleStockFrozenVO> list, String userId) throws Exception{
        stoManageService.frozenAndReset(list,1,userId);
    }

    @Override
    public void frozenReset(List<VehicleStockFrozenVO> list,String userId) throws Exception{
        stoManageService.frozenAndReset(list,0,userId);
    }

    @Override
    public PageInfo detail(String storageId,Integer pageNum,Integer pageSize) {
        return stoManageService.detail(storageId,pageNum,pageSize);
    }

    @Override
    public PageInfo<StoManageVO> findPageByVO(StoManageVO stoManageVO, Integer pageNum, Integer pageSize) {
        PageInfo<StoManageVO> pageInfo = stoManageService.pageByVo(stoManageVO, pageNum, pageSize);
        return pageInfo;
    }

    @Override
    public Object findTreeList() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        return stoManageService.findTreeList();
    }

    /**
     * 渠道商新增仓库
     * @param stoManageAddVO
     * @return
     */
    @Override
    public String partnerStorage(StoManageAddVO stoManageAddVO) throws Exception{
        StoManageEditVO stoManageEditVO = new StoManageEditVO();
        stoManageEditVO.setStorageName(stoManageAddVO.getStorageName());
        stoManageEditVO.setStorageFullName(stoManageAddVO.getStorageName());
        stoManageEditVO.setStorageLocation(stoManageAddVO.getStorageLocation());
        stoManageEditVO.setStorageType("1");//仓库类型:仓库
        stoManageEditVO.setStorageOrgType("2");//仓库组织类型:渠道商
        saveOrUpdate(stoManageEditVO);
        return stoManageEditVO.getStorageCode();
    }

    /**
     * 库区列表
     * @return
     */
    @Override
    public List<StoManageAreaVO> areaList() {
        QueryWrapper<StoManage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("STORAGE_TYPE","2");
        List<StoManage> list = stoManageService.list(queryWrapper);
        List<StoManageAreaVO> list1 = new ArrayList<>();
        StoManageAreaVO stoManageAreaVO = new StoManageAreaVO();
        stoManageAreaVO.setAreaCode("-1");
        stoManageAreaVO.setAreaname("全部在库车辆");
        list1.add(stoManageAreaVO);
        if(list != null && list.size() > 0){
            for (StoManage stoManage : list){
                StoManageAreaVO stoManageAreaVO1 = new StoManageAreaVO();
                stoManageAreaVO1.setAreaCode(stoManage.getStorageCode());
                stoManageAreaVO1.setAreaname(stoManage.getStorageFullName());
                list1.add(stoManageAreaVO1);
            }
        }
        return list1;
    }

    /**
     * 导出库位冻结明细
     * @return
     * @throws Exception
     */
    @Override
    public List<VehicleStockFrozenListVO> exportFrozenHis() throws Exception {
        return stoManageService.exportFrozenHis();
    }

    /**
     * 校验库位名称不可重复
     * @param stoManage
     * @throws Exception
     */
    private void checkStorageFourName(StoManage stoManage) throws Exception {
        String storageTypeT = stoManage.getStorageType();
        if(StringUtils.isNotEmpty(storageTypeT) && storageTypeT.equals("4")){
            QueryWrapper<StoManage> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("STORAGE_FULL_NAME",stoManage.getStorageFullName());
            if(StringUtils.isNotEmpty(stoManage.getStorageId())){
                queryWrapper.ne("STORAGE_ID",stoManage.getStorageId());
            }
            List<StoManage> list = stoManageService.list(queryWrapper);
            if(list != null && list.size() > 0){
                throw new Exception("操作失败,库位名称:"+stoManage.getStorageFullName()+"已存在!");
            }
        }
    }

}
